#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <semaphore.h>
#include <pthread.h>
template<class T>
class ringqueue{
    private:
        void P(sem_t &s){
            sem_wait(&s);
        }
        void V(sem_t &s){
            sem_post(&s);
        }
    public:
        ringqueue(int sum = 5)
        : _ring_queue(sum)
        , _sum(sum)
        , _c_step(0)
        , _p_step(0)
        {
            sem_init(&_data_sem, 0, 0);
            sem_init(&_space_sem, 0, sum);
            pthread_mutex_init(&_c_mutex, nullptr);
            pthread_mutex_init(&_p_mutex, nullptr);
        }
        void Push(const T& val){
            P(_space_sem);
            pthread_mutex_lock(&_p_mutex);
            _ring_queue[_p_step] = val;
            _p_step++;
            _p_step %= _sum;
            pthread_mutex_unlock(&_p_mutex);
            V(_data_sem);
        }
        void Pop(T* val){
            P(_data_sem);
            pthread_mutex_lock(&_c_mutex);
            *val = _ring_queue[_c_step];
            _c_step++;
            _c_step %= _sum;
            pthread_mutex_unlock(&_c_mutex);
            V(_space_sem);
        }
        ~ringqueue(){
            sem_destroy(&_data_sem);
            sem_destroy(&_space_sem);
        }
    private:
        std::vector<T> _ring_queue;
        int _sum;
        int _c_step;
        int _p_step;
        sem_t _data_sem;
        sem_t _space_sem;
        pthread_mutex_t _c_mutex;
        pthread_mutex_t _p_mutex;
};